package log_callback_handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"peilian-api/utils/format"
	"peilian-api/utils/tools"
	"strconv"
)

func LogCallback(c *gin.Context) {
	log := new(tables.LogCallback)
	if err := c.ShouldBindJSON(log); err != nil {
		format.NewResponseJson(c).Err(400, err.Error())
		return
	}
	addUserId := func() error {
		logJson := make(map[string]interface{})
		if err := json.Unmarshal([]byte(log.LogText), &logJson); err != nil {
			return err
		}
		authToken := c.Request.Header.Get("AuthenticationToken")
		if authToken == "" {
			logJson["user_id"] = strconv.Itoa(0)
		} else {
			_, claims, err := tools.ParseToken(authToken)
			if err != nil {
				logJson["user_id"] = strconv.Itoa(0)
			} else {
				logJson["user_id"] = strconv.Itoa(int(claims.UserId))
			}
		}
		logLastJson, _ := json.Marshal(logJson)
		log.LogText = string(logLastJson)
		log.UserId = logJson["user_id"].(string)
		return nil
	}
	if err := addUserId(); err != nil {
		format.NewResponseJson(c).Err(400, "日志应该为json格式")
		return
	}
	if log.IsCount {
		result := variable.DB.MySQL.Model(&tables.LogCallback{}).
			Where("type=? and log_text=?", log.Type, log.LogText).
			Update("count", gorm.Expr("count+?", 1))
		if result.Error != nil {
			format.NewResponseJson(c).Err(400, result.Error.Error())
			return
		}
		if result.RowsAffected > 0 {
			format.NewResponseJson(c).SuccessJson()
			return
		}
	}
	log.Count = 1
	if err := variable.DB.MySQL.Create(log).Error; err != nil {
		format.NewResponseJson(c).Err(400, err.Error())
		return
	}

	format.NewResponseJson(c).SuccessJson()
}
